﻿using MvcWechat.Common;
using MvcWechat.Services;
using MvcWechat.XcxHelper;
using MvcWechat.XcxHelper.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace MvcWechat.Controllers
{
    /// <summary>
    /// 小程序
    /// </summary>
    public class XcxController : BaseController
    {
        //
        // GET: /Xcx/ 
        public JsonResult UserInfo()
        {
            //var jsCode = "023iym2f2ZvWsC0Emr4f2FUA2f2iym21";
            ////var s=SnsApi.JsCode2Json(XcxConfig.AppID, XcxConfig.AppSecret, "023iym2f2ZvWsC0Emr4f2FUA2f2iym21");
            //var openid = "oD78P0XGqAtOps-eXpxTRlFT-KSE";
            //var session_key = "LAAIrM05vPM6Mw4YEftFRw==";
            ////var rawData = "{\"nickName\":\"麦多多\",\"gender\":2,\"language\":\"zh_CN\",\"city\":\"Shenzhen\",\"province\":\"Guangdong\",\"country\":\"China\",\"avatarUrl\":\"https://wx.qlogo.cn/mmopen/vi_32/AkI7IRfKPvp9B0Iax7mFnJqbnhC800eheTqDxrlfFxgMia6Dqacn2yDmDunGjVMCp064GblQ7euQ6zoXUicMmPOw/132\"}";
            //var iv = "z3H1B3luDUru04GNbJmJng==";
            //var encryptedData = "YZf1fPJ0NvikEO7B4sGzHkOf8QRcpFcic7nS9acKNNKulf7ym4OxCHdrbB7AtLOysfKSz6mynoNiZvoSk4q4tFQmCfyqMLzIG4tj0reWSmWclfK3DDXEWZZLdYr+sPR5nbuekrRRiELpJFIf6SzUfIhHw5IqYdb3LgzyxqNPxpREh6vU5ypvOlNqsrtDgQU9wsHh5NFw3XSrAegWggMFD38eSWJ8A2VcaCRL5FB5ozSqolrKouWt6s4rCf6hmxWQUC5VWVib5QMh17oNJarXGNJZmr5PeHPHrPzKVeyMyoDa21Q9ijgDPsnsXBOA+0mqKO0Rv2eXL8aXa0B5A+NS5xqY9+VqlUC+x5AYecX1m7d3L3rfPQel2W16hq7XBZPebW5yfQ7bDWliVFt7u/W2GjyaUaafRGFbBRMVxwsuJyaMnM/572y5cNH4r4VdaujaDOOQx6HA1RBPSCHUh/jOW2hwcfoTYh+niVslQTnJbkM=";
            //var e = SnsApi.DecodeEncryptedData(session_key, encryptedData, iv);
            ////"{\"openId\":\"oD78P0XGqAtOps-eXpxTRlFT-KSE\",\"nickName\":\"麦多多\",\"gender\":2,\"language\":\"zh_CN\",\"city\":\"Shenzhen\",\"province\":\"Guangdong\",\"country\":\"China\",\"avatarUrl\":\"https://wx.qlogo.cn/mmopen/vi_32/AkI7IRfKPvp9B0Iax7mFnJqbnhC800eheTqDxrlfFxgMia6Dqacn2yDmDunGjVMCp064GblQ7euQ6zoXUicMmPOw/132\",\"watermark\":{\"timestamp\":1536548215,\"appid\":\"wx143cdda37487e9ac\"}}"
            ////signature = sha1(rawData + session_key)

            //var inputJson = ManagerJson.ToJson(ControllerContext.RequestContext.HttpContext.Request.InputStream);
            //Logger.Debug(this.GetType(), "UserInfo inputJson: " + inputJson);
            return Json("ok");
        }
        const string msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\"}";
        public JsonResult GetOpenIdByJsCode()
        {
            var msg = string.Empty;
            try
            {
                var inputDict = GetInputDict();
                DebugLog("GetOpenIdByJsCode:inputJson" + JsonConvert.SerializeObject(inputDict));
                if (inputDict.ContainsKey("code"))
                {
                    if (XcxConfigs.listConfigSettings.Count > 0 && inputDict.ContainsKey("TagKey"))
                    {
                        var key = inputDict["TagKey"].ToString();
                        var info = SnsApi.JsCode2Json(XcxConfigs.listConfigSettings[key].AppIDByXcx, XcxConfigs.listConfigSettings[key].AppSecretByXcx, inputDict["code"].ToString());
                        DebugLog("GetOpenIdByJsCode:info" + JsonConvert.SerializeObject(info));
                        if (string.IsNullOrEmpty(info.openid))
                            return Json(msgInfo.Replace("#code", "false").Replace("#msg", "openid为空 APPID：" + XcxConfigs.listConfigSettings[key].AppIDByXcx + ",AppSecret:" + XcxConfigs.listConfigSettings[key].AppSecretByXcx + " ,code:" + inputDict["code"]));
                        msg = msgInfo.Replace("#code", "true").Replace("#msg", info.openid);
                    }
                    else
                    {
                        msg = msgInfo.Replace("#code", "false").Replace("#msg", "未获取到AppID");
                    }
                }
                else
                    msg = msgInfo.Replace("#code", "false").Replace("#msg", "Code参数错误！");
            }
            catch (Exception ex)
            {
                ErrorLog(ex, "GetOpenIdByJsCode");
                msg = msgInfo.Replace("#code", "false").Replace("#msg", ex.Message);
            }
            return Json(msg);
        }
        public JsonResult SaveUserInfo()
        {
            try
            {
                var inputJson = GetInputDict();
                DebugLog("inputJson:" + JsonConvert.SerializeObject(inputJson));
                return SaveUserInfoPre(inputJson);
            }
            catch (Exception ex)
            {
                ErrorLog(ex, "SaveUserInfo");
                return Json(msgInfo.Replace("#code", "false").Replace("#msg", ex.Message));
            }
        }


        public JsonResult SaveUserInfoTest()
        {
            try
            {
                var rawData = "{\"openId\":\"oD78P0XGqAtOps-eXpxTRlFT-KSE\",\"rawData\":{\"nickName\":\"麦多多\",\"gender\":2,\"language\":\"zh_CN\",\"city\":\"Shenzhen\",\"province\":\"Guangdong\",\"country\":\"China\",\"avatarUrl\":\"https://wx.qlogo.cn/mmopen/vi_32/AkI7IRfKPvp9B0Iax7mFnJqbnhC800eheTqDxrlfFxgMia6Dqacn2yDmDunGjVMCp064GblQ7euQ6zoXUicMmPOw/132\"}}";
                var inputJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(rawData);
                DebugLog("inputJson:" + inputJson);
                return SaveUserInfoPre(inputJson);
            }
            catch (Exception ex)
            {
                ErrorLog(ex, "SaveUserInfo");
                return Json(msgInfo.Replace("#code", "false").Replace("#msg", ex.Message), JsonRequestBehavior.AllowGet);
            }
        }

        private JsonResult SaveUserInfoPre(Dictionary<string, object> inputJson)
        {
            if (inputJson.ContainsKey("openId") || inputJson.ContainsKey("rawData"))
            {
                XcxUserInfo xcxInfo = JsonConvert.DeserializeObject<XcxUserInfo>(inputJson["rawData"].ToString());
                xcxInfo.openId = inputJson["openId"].ToString();
                xcxInfo.remark = "小程序";
                //系统格式（微信格式）
                var baseUserInfo = JsonConvert.SerializeObject(xcxInfo).Replace("openId", "openid")
                    .Replace("nickName", "nickname").Replace("gender", "sex").Replace("avatarUrl", "headimgurl");
                DebugLog("baseUserInfo:" + baseUserInfo);
                var tagkey = inputJson.ContainsKey("TagKey") ? inputJson["TagKey"].ToString() : CommonPage.getKey();
                var v = BasicAPI.AddUserInfo(tagkey, baseUserInfo);
                DebugLog("AddUserInfo:" + v);
                var customerId = new ServiceController().GetCustomerIdByOpenid(xcxInfo.openId).ToString();
                //if (v)
                //{
                return Json(msgInfo.Replace("#code", "true").Replace("#msg", customerId));
                //}
                //else {
                //    return Json(msgInfo.Replace("#code", "false").Replace("#msg", "添加失败"));
                //}
            }
            else
                return Json(msgInfo.Replace("#code", "false").Replace("#msg", "参数错误！！"));
        }
        /// <summary>
        /// 获取用户访问小程序日周月留存
        /// https://developers.weixin.qq.com/miniprogram/dev/api/getAnalysisDailyRetain.html
        /// </summary>
        /// <param name="dateType"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetAnalysisDailyRetain(string dateType)
        {
            switch (dateType.ToLower())
            {
                case "daily":
                    return Json(await PostResultByUrl(XcxConfigs.GetAnalysisDailyRetainUrl));
                case "monthly":
                    return Json(await PostResultByUrl(XcxConfigs.GetAnalysisMonthlyRetainUrl));
                case "weekly":
                    return Json(await PostResultByUrl(XcxConfigs.GetAnalysisWeeklyRetainUrl));
            }
            return Json("error");
        }
        /// <summary>
        /// 获取用户访问小程序数据日周月趋势
        /// https://developers.weixin.qq.com/miniprogram/dev/api/getAnalysisDailyVisitTrend.html
        /// </summary>
        /// <param name="dateType"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetAnalysisDailyTrend(string dateType)
        {
            switch (dateType.ToLower())
            {
                case "daily":
                    return Json(await PostResultByUrl(XcxConfigs.GetAnalysisDailyVisitTrendUrl));
                case "monthly":
                    return Json(await PostResultByUrl(XcxConfigs.GetAnalysisMonthlyVisitTrendUrl));
                case "weekly":
                    return Json(await PostResultByUrl(XcxConfigs.GetAnalysisWeeklyVisitTrendUrl));

            }
            return Json("error");
        }
        /// <summary>
        /// 获取小程序新增或活跃用户的画像分布数据。时间范围支持昨天、最近7天、最近30天。其中，新增用户数为时间范围内首次访问小程序的去重用户数，活跃用户数为时间范围内访问过小程序的去重用户数。
        /// https://developers.weixin.qq.com/miniprogram/dev/api/getAnalysisUserPortrait.html
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetAnalysisUserPortrait()
        {
            return Json(await PostResultByUrl(XcxConfigs.GetAnalysisUserPortraitUrl));
        }
        /// <summary>
        /// 获取用户小程序访问分布数据
        /// https://developers.weixin.qq.com/miniprogram/dev/api/getAnalysisVisitDistribution.html
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetAnalysisVisitDistribution()
        {
            return Json(await PostResultByUrl(XcxConfigs.GetAnalysisVisitDistributionUrl));
        }

        /// <summary>
        /// 访问页面。目前只提供按 page_visit_pv 排序的 top200。
        /// </summary>
        /// https://developers.weixin.qq.com/miniprogram/dev/api/getAnalysisVisitPage.html
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetAnalysisVisitPage()
        {
            return Json(await PostResultByUrl(XcxConfigs.GetAnalysisVisitPageUrl));
        }

        public async Task<dynamic> PostResultByUrl(string url)
        {
            return await Util.HttpRequestPost(ParsePartUrlByToken(url), GetInputJson());
        }

        [HttpGet]
        public string GetCurrentMenus()
        {
            return msgInfo.Replace("#code", "true").Replace("#msg", CommonPage.GetSectionConfig());
        }

        public void ErrorLog(Exception ex, string info = "error")
        {
            Logger.Error(this.GetType(), string.Format("error:{0}--ex.Message:{1},ex.InnerException:{2},ex.StackTrace:{3} ", info, ex.Message, ex.InnerException, ex.StackTrace));
        }
        public void DebugLog(string info = "error")
        {
            Logger.Error(this.GetType(), string.Format("debug:{0}", info));
        }


    }

}
